package org.example2;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *  较短的数组,读取客户端数据,最终将其写到 ByteArrayOutputStream 中,
 *  最后再转变为数组,进而转成字符串.
 *
 *   注意:只有当客户端执行socket.close方法或 socket.shutdownOutput 方法,
 *   服务端才能通过读到 -1 ,从而跳出循环
 *   inputStream.read(bytes)) != -1
 *
 */

public class SingleStringServer {
    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("---------------服务器准备好了------------------");
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        System.out.println(inputStream.getClass().getName());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] bytes = new byte[94];
        int len=0;
        while ((len = inputStream.read(bytes)) != -1 ) {
            System.out.println("进来了-- len is "+len);

            // len为-1时,报错 IndexOutOfBoundsException ,数组长度不能为负数
            baos.write(bytes, 0, len);
        }

        System.out.println("读取结束后的len is " + len + "------------毫秒值:"+System.currentTimeMillis());


        byte[] bytes1 = baos.toByteArray();
        String result = new String(bytes1);

        String hostAddress = socket.getInetAddress().getHostAddress();

        System.out.println(hostAddress + "发来了信息:" + result);
        System.out.println("最后一个字节是:"+bytes1[bytes1.length-1]);

//        socket.close();
    }
}
